package com.cee.service.Impl;

import com.cee.common.result.ResultCodeEnum;
import com.cee.dto.OneTwoTypeDTO;
import com.cee.exception.CeeException;
import com.cee.model.*;
import com.cee.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;

@Slf4j
@Service
@Transactional
public class ImportExcelServiceImpl implements ImportExcelService {

    @Autowired
    private OneSelectService oneSelectService;
    @Autowired
    private ManySelectService manySelectService;
    @Autowired
    private JudgeService judgeService;
    @Autowired
    private CompletionService completionService;
    @Autowired
    private ShortAnswerService shortAnswerService;
    @Autowired
    private OneTwoTypeService oneTwoTypeService;

    @Autowired
    private OptionOneSelectService optionOneSelectService;
    @Autowired
    private OptionJudgeService optionJudgeService;
    @Autowired
    private OptionManySelectService optionManySelectService;

    @Override
    public void importExcel(MultipartFile file) throws Exception{
        if (file.getSize() ==0 || file == null){
            throw new CeeException(ResultCodeEnum.ERROR_801);
        }

        String fileName = file.getOriginalFilename();


        if ( !(fileName.endsWith(".xls") || fileName.endsWith(".xlsx")) ){
            throw new CeeException(ResultCodeEnum.ERROR_802);
        }


        log.info("开始上传，文件名称=", fileName);

        InputStream inputStream = file.getInputStream();

        Integer lastRowNum = 0;
        Sheet sheet = null;

        try{

            if (fileName.endsWith(".xls")){
                HSSFWorkbook workbook = new HSSFWorkbook(inputStream);
                //读取第一张sheet
                sheet = workbook.getSheetAt(0);
                lastRowNum = sheet.getLastRowNum();
            }
            else if(fileName.endsWith(".xlsx")){
                XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
                sheet = workbook.getSheetAt(0);
                lastRowNum = sheet.getLastRowNum();
            }
        }catch (Exception e){
            throw new CeeException("EXCEL文件加密错误，请解密上传！", 806);
        }


        String errorStr = "";

        log.info("文件名称：" + fileName+ "，总行数：" + lastRowNum + "行");

        for (int rowNum=1; rowNum < lastRowNum; rowNum++){

            Row row = sheet.getRow(rowNum);

            String jobType = row.getCell(0).getStringCellValue();// 类型1
            String jobType2 = row.getCell(1).getStringCellValue();// 类型2

            String examType = row.getCell(2).getStringCellValue().trim();// 题型

            if (StringUtils.isEmpty(jobType) || StringUtils.isEmpty(jobType2) || StringUtils.isEmpty(examType)){
                log.info("类型为空，不能上传");
                throw new CeeException(ResultCodeEnum.ERROR_803);
            }

            OneTwoTypeDTO oneTwoTypeDTO = oneTwoTypeService.getOneTwoTypeByStr(jobType, jobType2);

            // 验证类型是否存在
            if (oneTwoTypeDTO == null){
                log.info("第" + (rowNum+1) + "行，上传错误。类型1，类型2在数据库不存在");
                throw new CeeException("第" + (rowNum+1) + "行，上传错误。类型1，类型2在数据库不存在", ResultCodeEnum.ERROR_805.getCode());
            }

            String tilte = row.getCell(3).getStringCellValue();
            String answer = row.getCell(4).getStringCellValue();
            String option_a = row.getCell(8).getStringCellValue();
            String option_b = row.getCell(9).getStringCellValue();
            String option_c = row.getCell(10).getStringCellValue();
            String option_d = row.getCell(11).getStringCellValue();
            String option_e = row.getCell(12).getStringCellValue();
            String option_f = row.getCell(13).getStringCellValue();
            String option_g = row.getCell(13).getStringCellValue();

            if (StringUtils.equals(examType, "单选题")){

                if (StringUtils.isEmpty(tilte) || StringUtils.isEmpty(answer) || StringUtils.isEmpty(option_a) ||
                    StringUtils.isEmpty(option_b) || StringUtils.isEmpty(option_c) || StringUtils.isEmpty(option_d)) {

                   log.info("第" + (rowNum+1) + "行，单选题上传错误。题目、答案、选项A、B、C、D为空");
                   throw new CeeException("第" + (rowNum+1) + "行，单选题上传错误。题目、答案、选项A、B、C、D为空", ResultCodeEnum.ERROR_804.getCode());

                }

                OneSelect oneSelect = new OneSelect();
                oneSelect.setOneTypeId(oneTwoTypeDTO.getOneTypeId());
                oneSelect.setTwoTypeId(oneTwoTypeDTO.getTwoTypeId());
                oneSelect.setTitle(tilte);
                oneSelect.setAnswer(answer);

                log.info("上传保存单选题，oneSelect=", oneSelect);
                oneSelectService.saveOneSelect(oneSelect);

                // 添加选项
                OptionOneSelect optionOneSelect = new OptionOneSelect();
                optionOneSelect.setCeeOneSelectId(oneSelect.getId());

                if (StringUtils.isNotEmpty(option_a)){
                    optionOneSelect.setOptionDef("A");
                    optionOneSelect.setOptionText(option_a);
                    optionOneSelectService.addOptionOneSelect(optionOneSelect);
                }

                if (StringUtils.isNotEmpty(option_b)){
                    optionOneSelect.setOptionDef("B");
                    optionOneSelect.setOptionText(option_b);
                    optionOneSelectService.addOptionOneSelect(optionOneSelect);
                }

                if (StringUtils.isNotEmpty(option_c)){
                    optionOneSelect.setOptionDef("C");
                    optionOneSelect.setOptionText(option_c);
                    optionOneSelectService.addOptionOneSelect(optionOneSelect);
                }

                if (StringUtils.isNotEmpty(option_d)){
                    optionOneSelect.setOptionDef("D");
                    optionOneSelect.setOptionText(option_d);
                    optionOneSelectService.addOptionOneSelect(optionOneSelect);
                }

                if (StringUtils.isNotEmpty(option_e)){
                    optionOneSelect.setOptionDef("E");
                    optionOneSelect.setOptionText(option_e);
                    optionOneSelectService.addOptionOneSelect(optionOneSelect);
                }


            }

            if (StringUtils.equals(examType, "多选题")){

                ManySelect manySelect = new ManySelect();
                manySelect.setOneTypeId(oneTwoTypeDTO.getOneTypeId());
                manySelect.setTwoTypeId(oneTwoTypeDTO.getTwoTypeId());
                manySelect.setTitle(tilte);
                manySelect.setAnswer(answer);

                log.info("上传保存多选题，manySelect=", manySelect);
                manySelectService.saveManySelect(manySelect);


                OptionManySelect optionManySelect = new OptionManySelect();
                optionManySelect.setCeeManySelectId(manySelect.getId());

                if (StringUtils.isNotEmpty(option_a)){
                    optionManySelect.setOptionDef("A");
                    optionManySelect.setOptionText(option_a);
                    optionManySelectService.addOptionManySelect(optionManySelect);
                }

                if (StringUtils.isNotEmpty(option_b)){
                    optionManySelect.setOptionDef("B");
                    optionManySelect.setOptionText(option_b);
                    optionManySelectService.addOptionManySelect(optionManySelect);
                }

                if (StringUtils.isNotEmpty(option_c)){
                    optionManySelect.setOptionDef("C");
                    optionManySelect.setOptionText(option_c);
                    optionManySelectService.addOptionManySelect(optionManySelect);
                }

                if (StringUtils.isNotEmpty(option_d)){
                    optionManySelect.setOptionDef("D");
                    optionManySelect.setOptionText(option_d);
                    optionManySelectService.addOptionManySelect(optionManySelect);
                }

                if (StringUtils.isNotEmpty(option_e)){
                    optionManySelect.setOptionDef("E");
                    optionManySelect.setOptionText(option_e);
                    optionManySelectService.addOptionManySelect(optionManySelect);
                }

                if (StringUtils.isNotEmpty(option_f)){
                    optionManySelect.setOptionDef("F");
                    optionManySelect.setOptionText(option_f);
                    optionManySelectService.addOptionManySelect(optionManySelect);
                }

                if (StringUtils.isNotEmpty(option_g)){
                    optionManySelect.setOptionDef("G");
                    optionManySelect.setOptionText(option_g);
                    optionManySelectService.addOptionManySelect(optionManySelect);
                }
            }

            if (StringUtils.equals(examType, "判断题")){
                if (StringUtils.isEmpty(tilte) || StringUtils.isEmpty(answer) || StringUtils.isEmpty(option_a) ||
                        StringUtils.isEmpty(option_b)) {

                    log.info("第" + (rowNum+1) + "行，判断题上传错误。题目、答案、选项A、B为空");
                    throw new CeeException("第" + (rowNum+1) + "行，判断题上传错误。题目、答案、选项A、B为空", ResultCodeEnum.ERROR_804.getCode());

                }

                Judge judge = new Judge();
                judge.setOneTypeId(oneTwoTypeDTO.getOneTypeId());
                judge.setTwoTypeId(oneTwoTypeDTO.getTwoTypeId());
                judge.setTitle(tilte);
                judge.setAnswer(answer);

                log.info("上传保存判断题，judge=", judge);
                judgeService.saveJudge(judge);

                OptionJudge optionJudge = new OptionJudge();
                optionJudge.setCeeJudgeId(judge.getId());

                if (StringUtils.isNotEmpty(option_a)){
                    optionJudge.setOptionDef("A");
                    optionJudge.setOptionText(option_a);
                    optionJudgeService.addOptionJudge(optionJudge);
                }

                if (StringUtils.isNotEmpty(option_b)){
                    optionJudge.setOptionDef("B");
                    optionJudge.setOptionText(option_b);
                    optionJudgeService.addOptionJudge(optionJudge);
                }

            }

            if (StringUtils.equals(examType, "填空题")){
                if (StringUtils.isEmpty(tilte) || StringUtils.isEmpty(answer)) {
                    log.info("第" + (rowNum+1) + "行，填空题上传错误。题目、答案为空");
                    throw new CeeException("第" + (rowNum+1) + "行，填空题上传错误。题目、答案为空", ResultCodeEnum.ERROR_804.getCode());
                }

                Completion completion = new Completion();
                completion.setOneTypeId(oneTwoTypeDTO.getOneTypeId());
                completion.setTwoTypeId(oneTwoTypeDTO.getTwoTypeId());
                completion.setTitle(tilte);
                completion.setAnswer(answer);

                log.info("上传保存填空题，completion=", completion);
                completionService.saveCompletion(completion);

            }

            if (StringUtils.equals(examType, "简答题")){
                if (StringUtils.isEmpty(tilte) || StringUtils.isEmpty(answer)) {
                    log.info("第" + (rowNum+1) + "行，简答题上传错误。题目、答案为空");
                    throw new CeeException("第" + (rowNum+1) + "行，简答题上传错误。题目、答案为空", ResultCodeEnum.ERROR_804.getCode());
                }

                ShortAnswer shortAnswer = new ShortAnswer();
                shortAnswer.setOneTypeId(oneTwoTypeDTO.getOneTypeId());
                shortAnswer.setTwoTypeId(oneTwoTypeDTO.getTwoTypeId());
                shortAnswer.setTitle(tilte);
                shortAnswer.setAnswer(answer);

                log.info("上传保存简答题，shortAnswer=", shortAnswer);
                shortAnswerService.saveShortAnswer(shortAnswer);
            }


            // 题目类型必须为单选题、多选题、判断题、填空题、简答题
            if (!(StringUtils.equals(examType, "单选题") || StringUtils.equals(examType, "多选题") || StringUtils.equals(examType, "判断题") ||
            StringUtils.equals(examType, "填空题") || StringUtils.equals(examType, "简答题"))){
                log.info("第" + (rowNum+1) + "行，上传错误。题目类型必须为单选题、多选题、判断题、填空题、简答题");
                throw new CeeException("第" + (rowNum+1) + "行，上传错误。题目类型必须为单选题、多选题、判断题、填空题、简答题", ResultCodeEnum.ERROR_807.getCode());
            }

        }

        log.info("结束上传，文件名称=", fileName);

    }
}
